package com.dx.weichat.weichat.service;

import com.dx.weichat.weichat.entity.CommandType;
import com.dx.weichat.weichat.entity.TextMsg;
import com.dx.weichat.weichat.redisUtils.RedisUtil;
import com.dx.weichat.weichat.wechatUtils.JsonUtil;
import com.dx.weichat.weichat.wechatUtils.WSUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.Set;

/**
 * @author: dx
 * @date: 2018/10/7/0007
 * @description: 一般类型处理的Service(普通消息处理的Service)
 */
@Service
public class CommonMsgService {
	@Autowired
	private RedisUtil redisUtil;
	private static Logger logger = LoggerFactory.getLogger(CommonMsgService.class);
	/**
	 * @author:dx
	 * @date:2018/10/7/0007
	 * @time:16:41
	 * @description: 询问天气的处理方法
	 * @param textMsg
	 * @return 返回处理值
	 */
	public String handleWeather(String cityCode){
		String xmlInfo = WSUtil.getWeatherInfo(cityCode);
		StringBuilder finalResult = new StringBuilder();
		try {
			if(redisUtil.get(cityCode+"info")==null) {
				JSONArray result = XML.toJSONObject(xmlInfo).getJSONObject("ArrayOfString").getJSONArray("string");
				finalResult.append("************************************\n");
				finalResult.append("地区:" + result.get(0) + "\n");
				finalResult.append("更新时间:" + result.get(3) + "\n");
				finalResult.append(result.get(4) + "\n");
				finalResult.append("===天气情况:" + result.getString(7).split(" ")[1] + "===\n");
				finalResult.append("===温度区间:" + result.getString(8).replace("/", "~") + "===\n");
				finalResult.append(result.get(5) + "\n");
				finalResult.append(result.get(6) + "\n");
				finalResult.append("************************************\n");
				//存入redis 4小时过期 下次遇到此城市直接取出数据返回
				redisUtil.set(cityCode+"info", finalResult,Long.valueOf(redisUtil.get("expireTime").toString()));
			}else {
				finalResult.append(String.valueOf(redisUtil.get(cityCode+"info")));
				finalResult.append(MessageFormat.format("****缓存取出 过期时间{0}s****",redisUtil.getExpire(cityCode+"info")));
			}
		}catch (JSONException e){
			String cityName=String.valueOf(redisUtil.get(cityCode));
			//尝试另一个接口
			String jsonInfo=WSUtil.bakGetWeather(cityName);
			if(redisUtil.get(cityCode+"info")==null&&!"".equals(jsonInfo)) {
				JSONObject jsonResult = new JSONObject(jsonInfo);
				//获取信息成功则解析信息
				if (jsonResult.getInt("status") == 200) {
					JSONObject info = jsonResult.getJSONObject("data");
					JSONObject todayJsonInfo = info.getJSONArray("forecast").getJSONObject(0);
					finalResult.append("************************************\n");
					finalResult.append("####地区:" + jsonResult.getJSONObject("cityInfo").getString("city") + "####\n");
					finalResult.append("####日期:" + todayJsonInfo.getString("date") + "####\n");
					finalResult.append("####天气情况:" + todayJsonInfo.getString("type") + "####\n");
					finalResult.append("####温度:" + todayJsonInfo.getString("low").split(" ")[1] + "~" + todayJsonInfo.getString("high").split(" ")[1] + "####\n");
					finalResult.append("####湿度:" + info.get("shidu") + "####\n");
					finalResult.append("####日出时间:" + todayJsonInfo.getString("sunrise") + " am ####\n");
					finalResult.append("####日落时间:" + todayJsonInfo.getString("sunset") + " pm ####\n");
					finalResult.append("####风向:" + todayJsonInfo.getString("fx") + "####\n");
					finalResult.append("####风力:" + todayJsonInfo.getString("fl") + "####\n");
					finalResult.append("####空气质量:" + info.getString("quality") + "####\n");
					finalResult.append("更新时间:" + jsonResult.get("time") + "\n");
					finalResult.append("************************************\n");
				}
				//存入redis 4小时过期 下次遇到此城市直接取出数据返回
				redisUtil.set(cityCode+"info", finalResult,Long.valueOf(redisUtil.get("expireTime").toString()));
			}else if(redisUtil.get(cityCode+"info")!=null){
				finalResult.append(String.valueOf(redisUtil.get(cityCode+"info")));
				finalResult.append(MessageFormat.format("****缓存取出 过期时间{0}s****",redisUtil.getExpire(cityCode+"info")));
			}else{
				finalResult.append("暂不支持该城市");
			}
		}

		return finalResult.toString();
	}

	/**
	 * @author:dx
	 * @date:2018/10/8/0008
	 * @time:11:36
	 * @description:
	 * @param textMsg 文本消息对象
	 * @return
	 */
	public String processTextMsg(TextMsg receiveTextMsg){
		TextMsg responseTextMsg = new TextMsg("未识别的命令\n输入/?获取命令列表",receiveTextMsg);
		if(receiveTextMsg.getContent().contains(":")) {
			String[] receiveMsg= receiveTextMsg.getContent().split(":");
			switch (receiveMsg[0]){
				case CommandType.GETWEAHER:
					//获取天气
					responseTextMsg = new TextMsg(handleWeather(receiveMsg[1]), receiveTextMsg.getToUserName(), receiveTextMsg.getFromUserName());
					break;
				case CommandType.GETREDISVALUE:
					//获取redis中值
					responseTextMsg = new TextMsg(MessageFormat.format("========================\nvalue:{0}\n过期时间:{1}s\n=========================",redisUtil.get(receiveMsg[1]),redisUtil.getExpireTime(receiveMsg[1])),receiveTextMsg);
					break;
				case CommandType.SETREDIS:
					//设置redis中的值
					if(receiveMsg.length<3||"".equals(receiveMsg[1])||"".equals(receiveMsg[2])){
						responseTextMsg = new TextMsg("参数不全,请检查参数",receiveTextMsg);
					}else {
						boolean flag ;
						if(receiveMsg.length==3)
							flag=redisUtil.set(receiveMsg[1],receiveMsg[2]);
						else
							flag=redisUtil.set(receiveMsg[1],receiveMsg[2],Long.valueOf(receiveMsg[3]));  //有过期时间的
						responseTextMsg=flag?new TextMsg("success",receiveTextMsg):new TextMsg("failure",receiveTextMsg);
					}
					break;
				case CommandType.SETREDISTTL:
					//设置redis中值的过期时间
					if("".equals(receiveMsg[1])){
						responseTextMsg = new TextMsg("参数不全,请检查参数",receiveTextMsg);
					}else {
						boolean flag;
						flag = redisUtil.expire(receiveMsg[1], Long.parseLong(receiveMsg[2]));
						responseTextMsg = flag ? new TextMsg("success", receiveTextMsg) : new TextMsg("failure", receiveTextMsg);
					}
					break;
				case CommandType.GETALLFROMREDIS:
					//取出redis中所有的值
					Set<String> keys = redisUtil.keys();
					StringBuilder keysAll = new StringBuilder();
					for(String temp : keys){
						keysAll.append(temp).append("\n");
					}
					responseTextMsg = new TextMsg(keysAll.toString(),receiveTextMsg);
					break;
				default:
					break;
			}
		}else if(receiveTextMsg.getContent().equals("/?")){
			//获取命令列表
			responseTextMsg = new TextMsg(String.valueOf(redisUtil.get("commandList")),receiveTextMsg);
		}
		return JsonUtil.Obj2xmlByGson(responseTextMsg);
	}
}
